package com.datasecops.scannerservices.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.datasecops.scannerservices.enumerate.DBDrive;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * MySQl相关操作
 *
 * @author: SunLingzhi
 * @time: 2022/8/12 16:35
 */
@Slf4j
public class Mysql extends DBHelper {

    private static Mysql instance = null;

    public static Map<String, DruidDataSource> dataSourceMap = new HashMap<>();

    public static Mysql getInstance() {
        if (null == instance) {
            synchronized (Mysql.class) {
                if (null == instance) {
                    instance = new Mysql();
                }
            }
        }
        return instance;
    }

    public static Mysql getInstance(String ip, int port, String user, String password,String Instance) {
        //初始化数据源
        if (null == instance) {
            synchronized (Mysql.class) {
                if (null == instance) {
                    instance = new Mysql();
                }
            }
        }

        //如果map没有这个数据源，则新建
        if (!Mysql.getInstance().containsId(getSourceMapKey(ip, port,Instance))) {
            Mysql.getInstance().addDataSource(ip, port, user, password,Instance);
        }
        //初始化数据源
        return instance;
    }

    /**
     * 获取连接
     *
     * @param
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/15 11:37
     */
    @Override
    public Connection getConnection(String key) {
        Connection conn = null;
        try {
            DruidDataSource source = dataSourceMap.get(key);
            conn = source.getConnection();
            log.error("数据库连接前的值是:conn");
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("数据库连接时的错误是:"+e.getMessage());
        }
        return conn;
    }


    /**
     * 插入数据源
     * @param
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/15 11:13
     */
    @Override
    public void addDataSource(String ip, int port, String user, String password,String Instance) {
        //String url = "jdbc:mariadb://" + ip + ":" + port;
        //String url = "jdbc:mysql://" + ip + ":" + port;
        String url = "jdbc:mysql://" + ip + ":" + port + "/"+Instance+"?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=Asia/Shanghai";
        //String properties = "useUnicode=true;characterEncoding=UTF8;useSSL=false;serverTimezone=Asia/Shanghai";
        Properties prop = getCommonProp(user, password, DBDrive.MYSQL.getValue(), url, null);
        try {
            DruidDataSource druidDataSource = (DruidDataSource) DruidDataSourceFactory
                    .createDataSource(prop);

            putSourceMap(getSourceMapKey(ip, port,Instance), druidDataSource);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化创建连接池失败！");
        }
    }





    /**
     * 初始化数据源---initial
     *
     * @param
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/12 18:08
     */
    /*    private static void addDataSource(String ip, int port, String user, String password) {
        Properties prop = new Properties();
        prop.put("driver", DBDrive.MYSQL.getValue());
        prop.put("url", "jdbc:mysql://" + ip + ":" + port + "/dsm");
        prop.setProperty("connectionProperties", "useUnicode=true;characterEncoding=UTF8;useSSL=false;serverTimezone=Asia/Shanghai");
        prop.setProperty("username", user);
        prop.setProperty("password", password);
        prop.setProperty("initialSize", "3");
        prop.setProperty("maxActive", "6");
        prop.setProperty("minIdle", "1");
        prop.setProperty("maxWait", "60000");
        prop.setProperty("filters", "stat");
        prop.setProperty("timeBetweenEvictionRunsMillis", "35000");
        prop.setProperty("minEvictableIdleTimeMillis", "30000");
        prop.setProperty("testWhileIdle", "true");
        prop.setProperty("testOnBorrow", "false");
        prop.setProperty("testOnReturn", "false");
        prop.setProperty("poolPreparedStatements", "false");
        prop.setProperty("maxPoolPreparedStatementPerConnectionSize", "200");
        prop.setProperty("removeAbandoned", "true");

        try {
            DruidDataSource druidDataSource = (DruidDataSource) DruidDataSourceFactory
                    .createDataSource(prop);

            //put进Map
           // putSourceMap(getSourceMapKey(ip, port), druidDataSource);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化创建连接池失败！");
        }
    }*/

    /**
     * 判断数据源是否存在
     *
     * @param
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/15 11:09
     */
    @Override
    public boolean containsId(String id) {
        return dataSourceMap.containsKey(id);
    }

    /**
     * putMap
     *
     * @param
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/15 11:23
     */
    @Override
    public void putSourceMap(String sourceMapKey, DruidDataSource druidDataSource) {
        dataSourceMap.put(sourceMapKey, druidDataSource);
    }

    /**
     * removeMap
     *
     * @param
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/15 11:23
     */
    @Override
    public void removeSourceMap(String sourceMapKey) {
        dataSourceMap.remove(sourceMapKey);
    }
}
